<template>
	<div>
		<!-- 面包屑导航区域 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>商品列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片视图区域 -->
		<el-card>
			<el-row :gutter="20">
				<!-- 搜索商品输入框 -->
				<el-col :span="8">
					<el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getGoodsList">
						<el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
					</el-input>
				</el-col>
				<!-- 添加商品按钮 -->
				<el-col :span="3">
					<el-button type="primary" @click="goAddPage">添加商品</el-button>
				</el-col>
			</el-row>

			<!-- 表格区域 -->
			<el-table :data="goodsList" border stripe>
				<el-table-column type="index" label="#" width="40"></el-table-column>
				<el-table-column label="商品名称" prop="goods_name"></el-table-column>
				<el-table-column label="商品价格(元)" prop="goods_price" width="75"></el-table-column>
				<el-table-column label="商品重量" prop="goods_weight" width="70"></el-table-column>
				<el-table-column label="创建时间" width="160">
					<template slot-scope="scope">
						{{scope.row.add_time | dateFormat}}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="120">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.goods_id)"></el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGoods(scope.row.goods_id)"></el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页区域 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" background>
			</el-pagination>
		</el-card>

		<!-- 修改商品信息对话框 -->
		<el-dialog title="修改商品信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
			<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
				<el-form-item label="商品名称" prop="goods_name">
					<el-input v-model="editForm.goods_name"></el-input>
				</el-form-item>
				<el-form-item label="商品价格" prop="goods_price">
					<el-input v-model="editForm.goods_price"></el-input>
				</el-form-item>
				<el-form-item label="商品重量" prop="goods_weight">
					<el-input v-model="editForm.goods_weight"></el-input>
				</el-form-item>
				<el-form-item label="商品分类" prop="goods_cat">
					<el-cascader v-model="editForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange"></el-cascader>
				</el-form-item>
				<el-form-item label="商品数量" prop="goods_number">
					<el-input v-model="editForm.goods_number"></el-input>
				</el-form-item>
        <el-form-item label="商品介绍" prop="goods_introduce">
					<quill-editor v-model="editForm.goods_introduce"></quill-editor>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editGoods">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
  data() {
    return {
      // 商品列表
      goodsList: [],
      // 请求参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 总数据条数
      total: 0,
      // 控制修改对话框的展示与隐藏
      editDialogVisible: false,
      editForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: ''
      },
      // 修改表单的验证规则对象
      editFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_introduce: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }]
      },
      // 商品分类列表
      cateList: [],
      // 级联选择器的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 即将修改的商品 id
      editGoodsId: ''
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表数据
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取商品数据失败！')
      this.goodsList = res.data.goods
      this.total = res.data.total
      // console.log(this.goodsList, this.total)
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 点击添加按钮，导航跳转到添加商品页面
    goAddPage() {
      this.$router.push('/goods/add')
    },
    // 根据 id 移除对应的商品信息对象
    async removeGoods(goodsId) {
      const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return this.$message.info('已取消删除！')
      const { data: res } = await this.$http.delete('goods/' + goodsId)
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.getGoodsList()
      this.$message.success('删除成功！')
    },
    // 展示修改商品对话框
    async showEditDialog(id) {
      // 查询对应的商品信息
      const { data: res } = await this.$http.get('goods/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败！')
      // console.log(res)
      this.editForm.goods_name = res.data.goods_name
      this.editForm.goods_cat = res.data.goods_cat.split(',')
      this.editForm.goods_price = res.data.goods_price
      this.editForm.goods_number = res.data.goods_number
      this.editForm.goods_weight = res.data.goods_weight
      this.editForm.goods_introduce = res.data.goods_introduce
      this.getCateList()
      this.editGoodsId = res.data.goods_id
      this.editDialogVisible = true
    },
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败！')
      this.cateList = res.data
    },
    // 监听修改商品对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑并提交商品
    editGoods() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        const form = JSON.parse(JSON.stringify(this.editForm))
        form.goods_cat = form.goods_cat.join(',')
        const { data: res } = await this.$http.put('goods/' + this.editGoodsId, form)
        if (res.meta.status !== 200) return this.$message.error('更新商品信息失败！')

        this.editDialogVisible = false
        this.getGoodsList()
        this.$message.success('更新商品信息成功！')
      })
    },
    handleChange() {}
  }
}
</script>

<style lang="less" scoped>
</style>
